﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Timers;
using System.Configuration;

namespace SolarDumper
{
    public class Program
    {
  
        static void Main(string[] args)
        {
            double interval = 1000*60*15;

            using (Dumper dumper = new Dumper())
            {
                Console.Write(".");
                dumper.GetFiles();
            }
            Timer timer = new Timer(interval);
            timer.Elapsed += new ElapsedEventHandler(getImages);
            timer.Enabled = true;
            timer.Start();
            GC.KeepAlive(timer);
            
            Console.ReadLine();
        }

        private static void getImages(object sender, ElapsedEventArgs e)
        {
            using (Dumper dumper = new Dumper())
            {
                Console.Write(".");
                dumper.GetFiles();
            }
        }

      

        public class Dumper : IDisposable
        {
            private bool _disposed;
            private bool _configLoaded;
            private static readonly object ConfigLock = new object();
            public static string[] imgTypes;
            public static string imgWidth;
            public static string imgBaseUrl;
            public static string imgDumpDirectory;

            public Dumper()
            {
                EnsureConfig();
            }



            private void EnsureConfig()
        {
            if (_configLoaded)
                return;

            lock (ConfigLock)
            {
                if (!_configLoaded)
                {
                    imgDumpDirectory = AppDomain.CurrentDomain.BaseDirectory + @"\";

                    string imgTypesList = "0304";
                    if (ConfigurationManager.AppSettings.HasKeys())
                    {
                        imgTypesList = ConfigurationManager.AppSettings["imgTypesList"];
                    }

                    imgTypes = imgTypesList.Split(new Char[] { ',' });
                    imgWidth = "2048";
                    imgBaseUrl = "http://sdo.gsfc.nasa.gov/assets/img/latest/latest_";
                    _configLoaded = true;
                }
            }
        }

        /// <summary>
        /// Dispose()
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~Dumper()
        {
            Dispose(false);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    imgTypes = null;
                    imgWidth = null;
                    imgBaseUrl = null;
                    imgDumpDirectory = null;
                }
                _disposed = true;

            }
        }

            public void GetFiles()
            {


                using (WebClient wc = new WebClient())
                {
                    wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                    wc.Headers.Add("Cache-Control", "no-cache");

                    foreach (string imgType in imgTypes)
                    {

                        imgDumpDirectory = AppDomain.CurrentDomain.BaseDirectory + @"\";
                        string Url = imgBaseUrl + imgWidth + "_" + imgType + ".jpg";
                        string Filename = imgDumpDirectory + imgType + "_" + DateTime.Now.ToFileTime() + ".jpg";
                        wc.DownloadFile(Url, Filename);

                        var fileList = Directory.GetFiles(imgDumpDirectory, imgType + "*.jpg").Select(fn => new FileInfo(fn)).OrderByDescending(f => f.Name).ToArray();
                        if (fileList.Length > 1)
                        {
                            if (ComputeFileHash(fileList[0].ToString()) == ComputeFileHash(fileList[1].ToString()))
                            {
                                File.Delete(fileList[0].ToString());
                            }
                        }

                    }
                }

            }

            public static string ComputeFileHash(string fileName)
            {
                using (var stream = File.OpenRead(fileName))
                    return Encoding.UTF8.GetString(System.Security.Cryptography.MD5.Create().ComputeHash(stream));
            }

        }

    }
}
